package com.jd.org.service.impl;

import com.jd.basic.query.BaseQuery;
import com.jd.basic.utils.BaiduAuditUtils;
import com.jd.basic.utils.BusinessException;
import com.jd.basic.utils.MailUtils;
import com.jd.basic.utils.PageList;
import com.jd.org.domain.Employee;
import com.jd.org.domain.Shop;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.org.domain.ShopAuditLog;
import com.jd.org.dto.ShopAdminDto;
import com.jd.org.dto.ShopSettlementAgainDto;
import com.jd.org.dto.ShopSettlementDto;
import com.jd.org.mapper.EmployeeMapper;
import com.jd.org.mapper.ShopAuditLogMapper;
import com.jd.org.mapper.ShopMapper;
import com.jd.org.service.EmployeeService;
import com.jd.org.service.ShopService;
import com.jd.org.vo.ShopVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jd
 * @since 2023-02-28
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements ShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired

    private EmployeeService employeeService;
    @Autowired
    private JavaMailSender javaMailSender;
    // 店铺审核通过
    @Override
    public void settlement(ShopSettlementDto dto) {

        this.check(dto);
        this.save(dto);
    }
    // 审核通过，发送激活短信
    @Override
    public void sendAudit(ShopAuditLog shopAuditLog) {
        // 校验参数
        if (null == shopAuditLog){
            throw new BusinessException("请填写审核信息");
        }
        // 店铺入驻状态修改为待激活
        // 1、通过审核日志信息获取店铺id
        Long shopId = shopAuditLog.getShopId();
        if (null != shopId) {
            Shop shop = new Shop();
            // 绑定店铺id
            shop.setId(shopId);
            // 将店铺状态改为待激活
            shop.setState(1);
            // 修改shop表信息
            shopMapper.update(shop);
        }
        MailUtils.sendMail("1145698042@qq.com","恭喜你,店铺入驻信息已完成审核，请点击下方链接完成激活 " +
         "激活链接：http://localhost/shop/audit/" + shopAuditLog.getShopId(),"店铺审核结果通知");

//        try {
//            // 2发送邮箱激活链接
//            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//            // 2.1.设置发送人
//            simpleMailMessage.setFrom("1145698042@qq.com");
//            // 2.2.设置接收人
//            simpleMailMessage.setTo("1145698042@qq.com");
//            // 2.3.设置邮件主题
//            simpleMailMessage.setSubject("店铺审核结果通知");
//            // 2.4.设置邮件文本内容
//            simpleMailMessage.setText("恭喜你,店铺入驻信息已完成审核，请点击下方链接完成激活 " +
//                    "激活链接：http://localhost/shop/audit/" + shopAuditLog.getShopId());
//            // 2.5.发送邮件
//            javaMailSender.send(simpleMailMessage);
//        } catch (MailException e) {
//            e.printStackTrace();
//        }

        // 将日志存入shop_audit_log
        ShopAuditLog log = new ShopAuditLog();
        log.setId(shopAuditLog.getId());
        log.setShopId(shopAuditLog.getShopId());
        log.setNote(shopAuditLog.getNote());
        log.setAuditTime(new Date());
        // 暂未实现登录功能 审核人暂时为翔翔烂裤裆
        log.setAuditId(999);
        shopAuditLogMapper.add(log);

    }

    @Override
    public void sendReject(ShopAuditLog shopAuditLog) {
        // 校验参数
        if (null == shopAuditLog){
            throw new BusinessException("请填写审核信息");
        }
        // 1、通过审核日志信息获取店铺id
        Long shopId = shopAuditLog.getShopId();
        if (null != shopId) {
            Shop shop = new Shop();
            // 绑定店铺id
            shop.setId(shopId);
            // 将店铺状态改为审核不通过
            shop.setState(3);
            // 修改shop表信息
            shopMapper.update(shop);
        }
        MailUtils.sendMail("1145698042@qq.com", "很遗憾，店铺入驻信息审核未通过，请点击下方链接重新填写入住信息"  +
               " 激活链接：http://localhost:8081/#/registerAgain?shopId="  + shopAuditLog.getShopId(), "店铺审核结果通知");


        // 将日志存入shop_audit_log
        ShopAuditLog log = new ShopAuditLog();
        log.setId(shopAuditLog.getId());
        log.setShopId(shopAuditLog.getShopId());
        log.setNote(shopAuditLog.getNote());
        log.setAuditTime(new Date());
        // 暂未实现登录功能 审核人暂时为翔翔烂裤裆
        log.setAuditId(999);
        shopAuditLogMapper.add(log);

    }

    @Override
    public void settlementAgain(Shop shop) {
        String name  = shop.getName();
        // 百度AI校验
        // 校验店铺名称是否违规

        Boolean boo = BaiduAuditUtils.TextCensor(name);
        if (boo == false){
            throw new BusinessException("店铺名称不符合规范，请重新输入");
        }
        // 校验图片是否违规
        String dtoLogo = shop.getLogo();
        Boolean boo2 = BaiduAuditUtils.ImgCensor(dtoLogo);
        if (boo2 == false){
            throw  new BusinessException("图片违规，请另选一张");
        }

        shop.setState(0);
        shopMapper.update(shop);
    }

    @Override
    public Map<String, Object> echarts() {
        List<ShopVo> echarts = shopMapper.echarts();
        List<Integer> x = echarts.stream().map(ShopVo::getState).collect(Collectors.toList());
        List<Integer> y = echarts.stream().map(ShopVo::getNumber).collect(Collectors.toList());
        HashMap<String, Object> data = new HashMap<>();
        data.put("x",x);
        data.put("y",y);
        return data;
    }


    private void save(ShopSettlementDto dto) {
        Shop shop = new Shop();
        // 获取店铺信息
        shop = dto.getShop();
        // 将店铺信息传入店铺表中
        shopMapper.add(shop);
        // 获取管理员信息
        Employee employee1 = dto.getEmployee();
        // 获取店铺Id
        employee1.setShopId(shop.getId());
        // 将员工信息传入员工表中
        employeeService.add(employee1);
        // 将adminID传到店铺表
        Shop shop1 = new Shop();
        shop1.setId(shop.getId());
        shop1.setAdminId(employee1.getId());
        shopMapper.update(shop1);
    }



    private void check(ShopSettlementDto dto) {
        //        String name = dto.getName();
//        // 非空判断
//        if(StringUtils.isEmpty(name)){
//            throw new RuntimeException("店铺信息为空，请主动填写");
//        }
        // 格式判断 电话号码非格式化
//        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(16[5,6])|(17[0-8])|(18[0-9])|(19[1、5、8、9]))\\d{8}$";
//        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
//        String phone = dto.getAdmin().getPhone();
//        Matcher matcher = p.matcher(phone);
//        if (matcher.matches()){
//            throw  new BusinessException("请输入正确的电话号码");
//        }

        // 校验两次密码是否一致
        // 通过提交对象获取管理员对象
        ShopAdminDto admin = dto.getAdmin();
        // 校验两次密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())) {
            throw new BusinessException("两次密码不一致，请重新输入");
        }
        // 校验店铺名称是否注册过
        // 通过店铺名查询店铺信息
        Shop shop = shopMapper.findByName(dto.getName());
        // 如果店铺非空
        if (null != shop) {
            throw new BusinessException("店铺已注册，请登录");
        }
        // 百度AI校验
        // 校验店铺名称是否违规
        Shop dtoShop = dto.getShop();
        String name = dtoShop.getName();
        Boolean boo = BaiduAuditUtils.TextCensor(name);
        if (boo == false){
            throw new BusinessException("店铺名称不符合规范，请重新输入");
        }
        // 校验图片是否违规
        String dtoLogo = dto.getLogo();
        Boolean boo2 = BaiduAuditUtils.ImgCensor(dtoLogo);
        if (boo2 == false){
            throw  new BusinessException("图片违规，请另选一张");
        }
        // 校验店长名称是否违规
        String username = admin.getUsername();
        Boolean boo1 = BaiduAuditUtils.TextCensor(username);
        if (boo1 == false) {
            throw new BusinessException("账号名字违规");
        }
        String logo = dtoShop.getLogo();
        System.out.println(logo);



        //
        // 校验店铺管理者是否已经有一家店了
        // 通过店铺管理者查询其是否在员工表有注册且是否管理了店铺
        Employee employee = employeeMapper.findByName(admin.getUsername());
        if (null != employee && null != employee.getShopId()) {
            Shop shop1 = shopMapper.findByAdminId(employee.getId());
            if (shop1 != null) {
                throw new BusinessException("该店长已注册过店铺");
            }
        }




    }

    @Override
    public PageList<Shop> queryByPage(BaseQuery baseQuery) {
        PageList<Shop> PageList = super.queryByPage(baseQuery);
        // 获取店铺数据
        List<Shop> shops = PageList.getRows();
        // 遍历店铺获取shopID
        List<Long> shopIds = shops.stream().map(Shop::getId).collect(Collectors.toList());
        // 通过店铺id查询所有的店铺审核日志
        List<ShopAuditLog> auditLogs = shopAuditLogMapper.findByShopId(shopIds);
        // 将所有的店铺审核日志分组
        Map<Long, List<ShopAuditLog>> map = auditLogs.stream().collect(Collectors.groupingBy(ShopAuditLog::getShopId));
        // 将所有的店铺审核日志放到店铺对象里
        shops.stream().forEach(shop -> {
            List<ShopAuditLog> shopAuditLogs = map.get(shop.getId());
            shop.setAuditLogs(shopAuditLogs);
        });
        return PageList;
    }
}